package com.example.newspapersmanageos.Controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.newspapersmanageos.Entity.*;
import com.example.newspapersmanageos.Service.LoginService;
import com.example.newspapersmanageos.Service.UploadService;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private UploadService uploadService;

    @RequestMapping(value = "/uploadNewspaper")
    public String uploadNewspaper(@RequestParam("newspaperName") String newspaperName, @RequestParam("newspaperPrice") String newspaperPrice,
                           @RequestParam("publisher") String publisher, @RequestParam("date") String date,
                           @RequestParam("picture") MultipartFile picture, @RequestParam("title1") MultipartFile title1,
                           @RequestParam("title2") MultipartFile title2, @RequestParam("title3") MultipartFile title3) throws IOException {
        Date d = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
        String newN = dateFormat.format(d);
        picture = updatePictureName(picture, newN + "1");
        title1 = updatePictureName(title1, newN + "2");
        title2 = updatePictureName(title2, newN + "3");
        title3 = updatePictureName(title3, newN + "4");

        String imgPath = System.getProperty("user.dir") + "\\target\\classes\\static\\imgResources";
        String runingPath = System.getProperty("user.dir") + "\\src\\main\\resources\\static\\imgResources";
        fileCopy(imgPath, picture);
        fileCopy(runingPath, picture);
        fileCopy(imgPath, title1);
        fileCopy(runingPath, title1);
        fileCopy(imgPath, title2);
        fileCopy(runingPath, title2);
        fileCopy(imgPath, title3);
        fileCopy(runingPath, title3);

        Newspaper newspaper = new Newspaper(newspaperName, newspaperPrice, publisher, date, picture.getName());
        String r = uploadService.addNewspaperInfo(newspaper);
        int newspaperId = uploadService.getIdByImgName(picture.getName());
        Title t1 = new Title(title1.getName(),ocr(imgPath+"\\"+title1.getName()),newspaperId);
        Title t2 = new Title(title2.getName(),ocr(imgPath+"\\"+title2.getName()),newspaperId);
        Title t3 = new Title(title3.getName(),ocr(imgPath+"\\"+title3.getName()),newspaperId);
        uploadService.addTitleInfo(t1);
        uploadService.addTitleInfo(t2);
        uploadService.addTitleInfo(t3);

        if (r.equals("保存成功")){
            return "redirect:/upload/newspaperInfo";
        }
        return "error";
    }

    //跳转到报刊信息管理界面
    @RequestMapping(value = "/newspaperInfo")
    public String newspaperInfo(HttpServletRequest request) {
        String page1 = request.getParameter("page");
        int pageNum = 1, pageSize = 1;
        InetAddress address = null;
        if (page1 != null && !page1.equals("")) {
            pageNum = Integer.parseInt(page1);
        }
        Page<ShowInfo> page = uploadService.getAllNewspaperInfo(pageNum, pageSize);
        request.setAttribute("page", page);
        return "newspaperInfo";
    }
    //文字识别
    public String ocr(String imgPath){
        Tesseract tesseract = new Tesseract();
        String root =  System.getProperty("user.dir");
        tesseract.setDatapath("D:\\2018GraduationProject\\ocr\\CharacterTraining\\jTessBoxEditorFX\\tesseract-ocr\\tessdata");
        // 简体中文：chi_sim，英文：eng
        tesseract.setLanguage("chi_sim");
        String result = null;
        try {
            result = tesseract.doOCR(new File(imgPath));
        } catch (TesseractException e) {
            e.printStackTrace();
        }
        return result;
    }

    //文件重命名
    public MultipartFile updatePictureName(MultipartFile multipartFile, String newName) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        String[] filename = originalFilename.split("\\.");
        //临时文件
        File file = File.createTempFile(filename[0], "." + filename[1]);
        multipartFile.transferTo(file);
        //重命名
        file = FileUtil.rename(file, newName, true, true);
        InputStream inputStream = new FileInputStream(file);
        //File转换成MultipartFile
        multipartFile = new MockMultipartFile(file.getName(), inputStream);
        //程序退出后删除临时文件
        file.deleteOnExit();
        return multipartFile;
    }

    //将文件写入本工程资源目录
    public Boolean fileCopy(String path, MultipartFile file) {
        if (file.isEmpty()) {
            return false;
        }
        String fileName = file.getName();
//        String fileName = file.getOriginalFilename();
        File dest = new File(new File(path).getAbsolutePath() + "\\" + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
